/*!
 * Ext JS Library 3.0.0
 * Copyright(c) 2006-2009 Ext JS, LLC
 * licensing@extjs.com
 * http://www.extjs.com/license
 */
Ext.onReady(function(){

    var sid = "";
    var sname = "";
    var did = "";
    var dname = "";

    var stops_store = new Ext.data.JsonStore({
        root: 'stops',
        totalProperty: 'total',
        idProperty: 'stopid',
        remoteSort: true,

        fields: [
        'stopid','name', 'description', 'latitude', 'longitude',
        {
            name: 'connections',
            type: 'int'
        }
        ],

        // load using script tags for cross domain, if the data in on the same domain as
        // this page, an HttpProxy would be better
        proxy: new Ext.data.HttpProxy({
            url: 'allStops.jsp'
        })
    });
    stops_store.setDefaultSort('name', 'asc');
    stops_store.load({
        params:{
            start:0,
            limit:100
        }
    });

    var searchbox = new Ext.form.TextField({
        name: 'search',
        width: 490,
        allowBlank: true
    });

    var button = new Ext.Button({
        name: 'searchbut',
        text: ' Search',
        width: 75,
        handler: function (){
            aKey = searchbox.getValue();
            store.load({
                params:{
                    start:0,
                    limit:10,
                    keyword: aKey
                }
            });
        }
    });

    var tb = new Ext.Toolbar();

    tb.add( searchbox, button);
    var start = new Ext.form.ComboBox({
        store: stops_store,
        displayField:'name',
        name: 'start',
        queryParam:'keyword',
        editable: true,
        width:300,
        typeAhead: false,
        pageSize:15,
        loadingText: 'Searching...',
        forceSelection: true,
        triggerAction: 'all',
        selectOnFocus:true,
        emptyText:'Select Stop...'
    });

    start.on('select', function() {
        sid = stops_store.getAt(start.selectedIndex).data.stopid;
        sname = stops_store.getAt(start.selectedIndex).data.name;

    } );

    var end = new Ext.form.ComboBox({
        store: stops_store,
        fieldLabel:'Destination',
        displayField:'name',
        name:'end',
        width:300,
        queryParam:'keyword',
        typeAhead: true,
        pageSize:15,
        loadingText: 'Searching...',
        forceSelection: true,
        triggerAction: 'all',
        emptyText:'Select Destination...',
        selectOnFocus:true
    });

    end.on('select', function() {
        did = stops_store.getAt(end.selectedIndex).data.stopid;
        dname = stops_store.getAt(end.selectedIndex).data.name;
    });
    var space = new Ext.form.Label({});
    
    var connWin = new Ext.Window({
        title: 'Select Connection',
        layout:'fit',
        width:320,
        height:120,
        modal:true,
        closeAction:'hide',
        plain: true,
        items: [space, start, space, end],
        buttons: [{
            text:'Save',
            handler: function() {
                

                alert(sid + ', ' + sname + ', ' + did + ', ' + dname );
                Ext.Ajax.request({
                    url:'saveConnection.jsp',
                    method: 'POST',
                    params: {
                        did:did,
                        sid:sid,
                        dname:dname,
                        sname:sname
                    },
                    success: function(responseObject) {
                        Ext.Msg.alert('Status', 'Saved');
                        connWin.hide();
                        store.load({
                            params:{
                                start:0,
                                limit:10
                            }
                        });

                    },
                    failure: function() {

                        Ext.Msg.alert('Status', 'Please try again later.');
                    }


                })

            }
        },{
            text: 'Close',
            handler: function(){
                connWin.hide();
            }
        }]
    });
    
    connWin.add(start);
    connWin.add(end);

    // create the Data Store
    var store = new Ext.data.JsonStore({
        root: 'connections',
        totalProperty: 'total',
        idProperty: 'id',
        remoteSort: true,

        fields: [
        'id','sid', 'sname', 'did', 'dname', 'departures'
        ],

        // load using script tags for cross domain, if the data in on the same domain as
        // this page, an HttpProxy would be better
        proxy: new Ext.data.HttpProxy({
            url: 'allConnections.jsp'
        })
    });
    store.setDefaultSort('sname', 'asc');
    // create the grid
    var mygrid = new Ext.grid.GridPanel({
        store: store,
        columns: [
        {
            header: "Stop",
            width: 240,
            dataIndex: 'sname',
            sortable: true
        },

        {
            header: "Destination",
            width: 240,
            dataIndex: 'dname',
            sortable: true
        },

        {
            header: "Deaprtures",
            width: 110,
            dataIndex: 'departures',
            sortable: true
        }
        ],
        renderTo:'grid',
        width:600,
        height:450,
        tbar: tb,
        bbar: new Ext.PagingToolbar({
            pageSize: 10,
            store: store,
            displayInfo: true,
            displayMsg: 'Displaying topics {0} - {1} of {2}',
            emptyMsg: "No stops found",

            items:[
            '-', {
                pressed: false,
                text: "Add",
                handler: function (){
                    connWin.show();
                }

            }, '-', {
                text:"Delete",
                handler: function (btn) {
                    var sm = mygrid.getSelectionModel();
                    var rec = sm.getSelected();
                    if (rec) {
                        //alert(rec.data.toSource() );
                        //alert(rec.id);

                        Ext.MessageBox.confirm('Delete Warning',
                            'Are you sure you want to delete connection between ' + rec.data.sname + ' and '+ rec.data.dname + '?', confirmDelete);
                    }

                }
            }

            ]
        })
    });

    function confirmDelete(btn){
        if (btn =='yes') {
            var sm = mygrid.getSelectionModel();
            var rec = sm.getSelected();
            var stopid = rec.id;
            Ext.Ajax.request({
                url:'deleteConnection.jsp',
                params:{
                    id: stopid
                },
                waitMsg:'Saving Data...',
                success: function (p, action) {
                    store.reload();
                },
                failure:function(p, action) {
                    Ext.MessageBox.alert('Message', 'Delete Failed');
                }

            });

        }
    };

    mygrid.on('rowdblclick', function(agrid, rowIndex, e) {
        var record = agrid.getStore().getAt(rowIndex);
        window.location.href='editConnection.jsp?id=' +record.get('id');
                
    });

    store.load({
        params:{
            start:0,
            limit:10
        }
    });
});



